﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.UI;

namespace System.Web.Mvc
{
    /// <summary>
    /// HtmlHelper extension methods
    /// </summary>
    public static class MenuHelper
    {
        /// <summary>
        /// Build a menu, based on the MvcSiteMap
        /// </summary>
        /// <param name="helper">HtmlHelper instance</param>
        /// <param name="menuCssClass">Menu CSS class</param>
        /// <param name="selectedMenuItemCssClass">Selected menu item CSS class</param>
        /// <returns>Html markup</returns>
        public static string Menu(this HtmlHelper helper, string menuCssClass, string selectedMenuItemCssClass)
        {
            return Menu(helper, true, false, menuCssClass, selectedMenuItemCssClass, null);
        }

        /// <summary>
        /// Build a menu, based on the MvcSiteMap
        /// </summary>
        /// <param name="helper">HtmlHelper instance</param>
        /// <param name="menuCssClass">Menu CSS class</param>
        /// <param name="selectedMenuItemCssClass">Selected menu item CSS class</param>
        /// <param name="menuHtmlAttributes">Html attributes for the outer unordered list</param>
        /// <returns>Html markup</returns>
        public static string Menu(this HtmlHelper helper, string menuCssClass, string selectedMenuItemCssClass, object menuHtmlAttributes)
        {
            return Menu(helper, true, false, menuCssClass, selectedMenuItemCssClass, menuHtmlAttributes);
        }

        /// <summary>
        /// Build a menu, based on the MvcSiteMap
        /// </summary>
        /// <param name="helper">HtmlHelper instance</param>
        /// <param name="showStartingNode">Show starting node?</param>
        /// <param name="startFromCurrentNode">Start from current node?</param>
        /// <param name="menuCssClass">Menu CSS class</param>
        /// <param name="selectedMenuItemCssClass">Selected menu item CSS class</param>
        /// <param name="menuHtmlAttributes">Html attributes for the outer unordered list</param>
        /// <returns>Html markup</returns>
        public static string Menu(this HtmlHelper helper, bool showStartingNode, bool startFromCurrentNode, string menuCssClass, string selectedMenuItemCssClass, object menuHtmlAttributes)
        {
            return Menu(helper, SiteMap.Provider.Name, showStartingNode, startFromCurrentNode, menuCssClass, selectedMenuItemCssClass, menuHtmlAttributes);
        }

        /// <summary>
        /// Build a menu, based on the MvcSiteMap
        /// </summary>
        /// <param name="helper">HtmlHelper instance</param>
        /// <param name="providerName">Provider name (can be used to specify SiteMap datasource)</param>
        /// <param name="menuCssClass">Menu CSS class</param>
        /// <param name="selectedMenuItemCssClass">Selected menu item CSS class</param>
        /// <returns>Html markup</returns>
        public static string Menu(this HtmlHelper helper, string providerName, string menuCssClass, string selectedMenuItemCssClass)
        {
            return Menu(helper, providerName, true, false, menuCssClass, selectedMenuItemCssClass, null);
        }

        /// <summary>
        /// Build a menu, based on the MvcSiteMap
        /// </summary>
        /// <param name="helper">HtmlHelper instance</param>
        /// <param name="providerName">Provider name (can be used to specify SiteMap datasource)</param>
        /// <param name="menuCssClass">Menu CSS class</param>
        /// <param name="selectedMenuItemCssClass">Selected menu item CSS class</param>
        /// <param name="menuHtmlAttributes">Html attributes for the outer unordered list</param>
        /// <returns>Html markup</returns>
        public static string Menu(this HtmlHelper helper, string providerName, string menuCssClass, string selectedMenuItemCssClass, object menuHtmlAttributes)
        {
            return Menu(helper, providerName, true, false, menuCssClass, selectedMenuItemCssClass, menuHtmlAttributes);
        }

        /// <summary>
        /// Build a menu, based on the MvcSiteMap
        /// </summary>
        /// <param name="helper">HtmlHelper instance</param>
        /// <param name="providerName">Provider name (can be used to specify SiteMap datasource)</param>
        /// <param name="showStartingNode">Show starting node?</param>
        /// <param name="startFromCurrentNode">Start from current node?</param>
        /// <param name="menuCssClass">Menu CSS class</param>
        /// <param name="selectedMenuItemCssClass">Selected menu item CSS class</param>
        /// <param name="menuHtmlAttributes">Html attributes for the outer unordered list</param>
        /// <returns>Html markup</returns>
        public static string Menu(this HtmlHelper helper, string providerName, bool showStartingNode, bool startFromCurrentNode, string menuCssClass, string selectedMenuItemCssClass, object menuHtmlAttributes)
        {
            return Menu(helper, providerName, showStartingNode, 0, startFromCurrentNode, menuCssClass, selectedMenuItemCssClass, menuHtmlAttributes);
        }

        /// <summary>
        /// Build a menu, based on the MvcSiteMap
        /// </summary>
        /// <param name="helper">HtmlHelper instance</param>
        /// <param name="startingNodeLevel">Starting node level</param>
        /// <param name="menuCssClass">Menu CSS class</param>
        /// <param name="selectedMenuItemCssClass">Selected menu item CSS class</param>
        /// <returns>Html markup</returns>
        public static string Menu(this HtmlHelper helper, int startingNodeLevel, string menuCssClass, string selectedMenuItemCssClass)
        {
            return Menu(helper, SiteMap.Provider.Name, false, startingNodeLevel, true, menuCssClass, selectedMenuItemCssClass, null);
        }

        /// <summary>
        /// Build a menu, based on the MvcSiteMap
        /// </summary>
        /// <param name="helper">HtmlHelper instance</param>
        /// <param name="startingNodeLevel">Starting node level</param>
        /// <param name="menuCssClass">Menu CSS class</param>
        /// <param name="selectedMenuItemCssClass">Selected menu item CSS class</param>
        /// <param name="menuHtmlAttributes">Html attributes for the outer unordered list</param>
        /// <returns>Html markup</returns>
        public static string Menu(this HtmlHelper helper, int startingNodeLevel, string menuCssClass, string selectedMenuItemCssClass, object menuHtmlAttributes)
        {
            return Menu(helper, SiteMap.Provider.Name, false, startingNodeLevel, false, menuCssClass, selectedMenuItemCssClass, menuHtmlAttributes);
        }

        /// <summary>
        /// Build a menu, based on the MvcSiteMap
        /// </summary>
        /// <param name="helper">HtmlHelper instance</param>
        /// <param name="providerName">Provider name (can be used to specify SiteMap datasource)</param>
        /// <param name="startingNodeLevel">Starting node level</param>
        /// <param name="menuCssClass">Menu CSS class</param>
        /// <param name="selectedMenuItemCssClass">Selected menu item CSS class</param>
        /// <returns>Html markup</returns>
        public static string Menu(this HtmlHelper helper, string providerName, int startingNodeLevel, string menuCssClass, string selectedMenuItemCssClass)
        {
            return Menu(helper, providerName, false, startingNodeLevel, false, menuCssClass, selectedMenuItemCssClass, null);
        }

        /// <summary>
        /// Build a menu, based on the MvcSiteMap
        /// </summary>
        /// <param name="helper">HtmlHelper instance</param>
        /// <param name="providerName">Provider name (can be used to specify SiteMap datasource)</param>
        /// <param name="startingNodeLevel">Starting node level</param>
        /// <param name="menuCssClass">Menu CSS class</param>
        /// <param name="selectedMenuItemCssClass">Selected menu item CSS class</param>
        /// <param name="menuHtmlAttributes">Html attributes for the outer unordered list</param>
        /// <returns>Html markup</returns>
        public static string Menu(this HtmlHelper helper, string providerName, int startingNodeLevel, string menuCssClass, string selectedMenuItemCssClass, object menuHtmlAttributes)
        {
            return Menu(helper, providerName, false, startingNodeLevel, true, menuCssClass, selectedMenuItemCssClass, menuHtmlAttributes);
        }

        /// <summary>
        /// Build a menu, based on the MvcSiteMap
        /// </summary>
        /// <param name="helper">HtmlHelper instance</param>
        /// <param name="providerName">Provider name (can be used to specify SiteMap datasource)</param>
        /// <param name="showStartingNode">Show starting node?</param>
        /// <param name="startFromCurrentNode">Start from current node?</param>
        /// <param name="startingNodeLevel">Starting node level</param>
        /// <param name="menuCssClass">Menu CSS class</param>
        /// <param name="selectedMenuItemCssClass">Selected menu item CSS class</param>
        /// <param name="menuHtmlAttributes">Html attributes for the outer unordered list</param>
        /// <returns>Html markup</returns>
        public static string Menu(this HtmlHelper helper, string providerName, bool showStartingNode, int startingNodeLevel, bool startFromCurrentNode, string menuCssClass, string selectedMenuItemCssClass, object menuHtmlAttributes)
        {
            // Check for provider
            if (SiteMap.Providers[providerName] == null)
            {
                throw new InvalidOperationException(string.Format("Unknown SiteMap provider: {0}", providerName));
            }

            // Helpers
            HttpContextBase httpContext = new HttpContextWrapper(HttpContext.Current);
            UrlHelper urlHelper = new UrlHelper(new RequestContext(httpContext, RouteTable.Routes.GetRouteData(httpContext)));

            // Html attributes
            IDictionary<string, object> attributes = new RouteValueDictionary(menuHtmlAttributes);
            
            //SiteMap.Providers[providerName].
            // Determine root node
            SiteMapNode relativeRootNode = null;
            if (startFromCurrentNode)
            {
                relativeRootNode = SiteMap.Providers[providerName].CurrentNode;
            }
            else
            {
                relativeRootNode = SiteMap.Providers[providerName].RootNode;
            }
            if (relativeRootNode == null)
            {
                return string.Empty;
            }

            // String builder
            System.IO.StringWriter sw=new System.IO.StringWriter();
            var writer = new HtmlTextWriter(sw);
            foreach (KeyValuePair<string, object> attr in attributes)
            {
                if (attr.Key.ToLowerInvariant() != "class")
                {
                    writer.AddAttribute(attr.Key, attr.Value.ToString());
                }
            }
            if (!string.IsNullOrEmpty(menuCssClass))
            {
                writer.AddAttribute("class", menuCssClass);
            }
            writer.RenderBeginTag(HtmlTextWriterTag.Ul);
            RenderChildSiteNode(relativeRootNode, writer, selectedMenuItemCssClass, urlHelper,startingNodeLevel,0);
            writer.RenderEndTag();
            return sw.ToString();
        }
        internal static void RenderChildSiteNode(SiteMapNode node, HtmlTextWriter writer, string selectedMenuItemCssClass, UrlHelper urlHelper, int startingNodeLevel,int currentNodeLevel)
        {
            SiteMapNode mvcNode = node;
            bool nodeVisible = true;

            // Node authorized?
            if (!node.IsAccessibleToUser(HttpContext.Current))
                nodeVisible = false;

            //// Node visible?
            //if (mvcNode != null && mvcNode.Visibility != MvcSiteMapNodeVisibility.Full)
            //    nodeVisible = false;
            // Render node
            if (nodeVisible && currentNodeLevel >= startingNodeLevel)
            {
                if (SiteMap.CurrentNode != null && (SiteMap.CurrentNode == node || SiteMap.CurrentNode.IsDescendantOf(node)))
                {
                    if (!string.IsNullOrEmpty(selectedMenuItemCssClass))
                    {
                        writer.AddAttribute("class", selectedMenuItemCssClass);
                    }
                }
                writer.RenderBeginTag(HtmlTextWriterTag.Li);

                string url = node.Url;
                if (url.StartsWith("~"))
                {
                    url = urlHelper.Content(node.Url);
                }
                if (url.Length == 0)
                {
                    url = "javascript:void(0)";
                }
                writer.AddAttribute(HtmlTextWriterAttribute.Href, url);
                writer.RenderBeginTag(HtmlTextWriterTag.A);
                
                //Read menu item name from resource file by Tony Qu
                string localizedString=ResourceHtmlHelpers.Resource("MENU", node.Title);
                if (string.IsNullOrEmpty(localizedString))
                    writer.Write(Microsoft.Security.Application.AntiXss.HtmlEncode(node.Title));
                else
                    writer.Write(localizedString);

                writer.RenderEndTag();
                if(node.ChildNodes.Count>0)
                    writer.RenderBeginTag(HtmlTextWriterTag.Ul);
                foreach (SiteMapNode child in node.ChildNodes)
                {
                    RenderChildSiteNode(child, writer, selectedMenuItemCssClass, urlHelper, startingNodeLevel, currentNodeLevel + 1);
                }
                if (node.ChildNodes.Count > 0)
                    writer.RenderEndTag();
                writer.RenderEndTag();
            }
            else
            {
                foreach (SiteMapNode child in node.ChildNodes)
                {
                    RenderChildSiteNode(child, writer, selectedMenuItemCssClass, urlHelper, startingNodeLevel, currentNodeLevel + 1);
                }                
            }
        }
        /// <summary>
        /// Get SiteMapNode level
        /// </summary>
        /// <param name="node">SiteMapNode to determine level for</param>
        /// <returns>SiteMapNode level</returns>
        public static int GetNodeLevel(SiteMapNode node)
        {
            int level = 0;
            while (node.ParentNode != null)
            {
                level++;
                node = node.ParentNode;
            }
            return level;
        }
    }
}